import {
  EventType,
  MenuId,
  messageId,
  type PostMessageEvent,
  type ContentMenuMessageEvent
} from '@shared/index'

/**
 * 通信凭证
 */
let extensionId: string | null = null

function sendMessage(event: PostMessageEvent) {
  extensionId && chrome.runtime.sendMessage(extensionId, { ...event, messageId })
}

chrome.runtime.onMessage.addListener((event: PostMessageEvent, sender) => {
  if (event?.messageId === messageId) {
    switch (event.type) {
      case EventType.CONNECT: {
        extensionId = sender.id!
        break
      }
      case EventType.CONTEXT_MENU: {
        onContentMenuMessage(event)
        break
      }
    }
  }
  return false
})

function onContentMenuMessage(event: ContentMenuMessageEvent) {
  switch (event.data) {
    case MenuId.DOWNLOAD: {
      break
    }
    case MenuId.PARSE_LIST: {
      break
    }
  }
}

window.addEventListener('keydown', (event) => {
  // ctrl + s
  if (event.ctrlKey && !event.repeat && event.key.toLowerCase() === 's') {
    event.preventDefault()
    const video = document.querySelector('video')
    if (video && /^https?:\/\//.test(video.currentSrc)) {
      console.log(video)
    }
  }
})
